
$( document ).ready(function() {
   		
	// Initialize sliders
	//$( "#slider" ).slider({min: 1, max: 100, animate: "fast", value: 0});
	$( "#slider" ).noUiSlider({range: [0, 100] , start: 0, handles: 1, step: 10, slide: function() {
		
		$("#slider_value_meters").html(Math.round($("#slider").val()));
		$("#slider_value_feet").html(Math.round($("#slider").val() * 3.280839895));

        $("#wheel_submit_button").attr("disabled", false);
    }});
	
	$( "#slider_pie" ).noUiSlider({range: [0,100], start: 1, handles: 1, step: 5, slide: function() {
        
		$("#slider_value_pie").html(Math.round($("#slider_pie").val()));
        $("#pie_submit_button").attr("disabled", false);
	}});
	
	
	$( "#slider_beer" ).noUiSlider({range: [0, 1500] , start: 0, handles: 1, step: 100, slide: function() {
        
        $("#slider_value_grams").html($("#slider_beer").val()/1000);
		var x = Math.round($("#slider_beer").val()) * 0.00220462;
		x = Math.floor(x * 100) / 100;
		$("#slider_value_pounds").html(x.toFixed(2));
		
        $("#beer_submit_button").attr("disabled", false);
	}});
	
	// Tell DB About your session
	$.post("/db_insert", {new_session: 'new_session'}, function (data) {
		
		$("#session_id").val(data);
	});
	 
	
	$("#slider_value_meters").html("1");
	$("#slider_value_feet").html("3");
	$("#slider_value_pie").html("1");
	$("#slider_value_grams").html("0");
	$("#slider_value_pounds").html("0.00");

	$('a.arrow').click(function(){
	    $('html, body').animate({
	        scrollTop: $( $.attr(this, 'href') ).offset().top
	    }, 500);
	    return false;
	});
	
	$("a[href='#bottom']").click(function() {
		  $("html, body").animate({ scrollTop: $(document).height() }, "slow");
		  return false;
		});

	$("a[href='#top']").click(function() {
		  $("html, body").animate({ scrollTop: 0 }, "slow");
		  return false;
		});

		
		// jQuery extension to support star ratings.	
	$.fn.stars = function(value) {
		//return $(this).each(function(value) {
			// Get the value
			var val = value; //parseFloat($(this).html());
			// Make sure that the value is in 0 - 5 range, multiply to get width
            //var normalizedval = val*5/100
			//var size = Math.max(0, (Math.min(5, normalizedval))) * 256;
			var size = val * 256 /100;
            // Create stars holder
			
            $("#showscore").html(0);
			// Replace the numerical value with stars
            $(this).children().animate(
                {
                    height:256-size
                },
                { 
                    duration: 1000,
                    step: function() {
                        $("#showscore").html(100-Math.round($("span.stars span").height()*100/256));
                    }
                });
		//});
	};	

	// Bind "enter" key in subscription email input to the "subscribe" button
	$("#subscribe_email_bottom").keypress(function(event){
		if(event.keyCode == 13){
			event.preventDefault();
			$("#sendsubscribe").click();
		}
	});
	
     $("a , button").on("click",function() { report_click( $(this).attr('id') );});
		
});

function wheel_submit() {
	
	//$("#wheel_image").fadeOut( function() {
	//	$("#after_submit").fadeIn();
	//	$("#wheel_question_div").hide();
	//});
	
	$("#wheel_question_div").fadeOut( function() {
		$("#after_submit").fadeIn();
	});
	
	var meters = Math.round($("#slider").val());
	var feet = Math.round(meters * 3.280839895);
	
	$("#user_answer_wheel").html(meters + " meters / " + feet + " feet");
	
	report_result("wheel", meters);
	
	calculate_user_score(meters, "wheel");
	
	//$("#wheel_submit_button").attr("disabled", true);
	//$("#wheel_submit_button").removeClass("button2");
	//$("#wheel_submit_button").addClass("buttondisable");
}

function pie_submit() {
	

	$("#pie_question_div").fadeOut( function() {
		$("#after_submit_pie").fadeIn();
	});
	
	var result = Math.round($("#slider_pie").val());
	
	$("#user_answer_pie").html(result + "%");
	
	report_result("pie", result);
	
	calculate_user_score(result, "pie");
}

function beer_submit() {
	
	$("#beer_question_div").fadeOut( function() {
		$("#after_submit_beer").fadeIn();
		
	});
	
	var grams = Math.round($("#slider_beer").val());
	
	var pounds = grams * 0.00220462;
	pounds = Math.floor(pounds * 100) / 100;
	
	$("#user_answer_beer").html(grams + " grams / " + pounds.toFixed(2) + " pounds");
	
	report_result("beer", grams);
	
	calculate_user_score(grams, "beer");
}

function report_click(source) {
	
	var id = $("#session_id").val();
    
    _gaq.push(['_trackEvent', "Button", "click", source,1, true]); 
    
	$.post("/db_insert", {click: "click", source: source, id: id});
}

function report_result(type, result) {
	
	$.post("/db_insert", {submit: "submit", type: type, result: result});
}

function subscribe_button() {
	
	
	//var email = $("#subscribe_email").val();
	
	email = $("#subscribe_email_bottom").val();
	
	
	if (IsEmail(email)) {
	
		$.post("/db_insert", {subscribe: "subscribe", email: email});
		
		$("#subscribe_form_bottom").hide();
		$("#subscrive_promise_bottom").hide();		
		$("#subscribe_thankyou_bottom").fadeIn();
	}
	else {
		$("#wrong_mail").html("Please insert a valid mail");
		$("#wrong_mail").show();
	}
}


function IsEmail(email) {
	  // var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	  var regex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

	  return regex.test(email);
}

function calculate_user_score(score, type) {
	
	$.post("/db_select", {user_score: "user_score", user_result: score, type: type}, function(data){
		
		// avg_beer user_beer
		var average  = data.split('#')[0];
		var better  = data.split('#')[1];
		
        var score=$("#totalscore").val();
        $("#totalscore").val(parseInt(score)+parseInt(better));
        
		generate_share(type,better);
		
		if (type == "beer") {
			var pounds = average * 0.00220462;
			pounds = Math.floor(pounds * 100) / 100;
	
			$("#avg_beer").html(average + " grams / " + pounds.toFixed(2) + " pounds");
			$(".user_beer").html(better);
		}
		else if (type == "pie") {
			$("#avg_pie").html(average + "%");
			$(".user_pie").html(better);
		}
		else if (type == "wheel") {
			var feet = Math.round(average * 3.280839895);
	
			$("#avg_wheel").html(average + " meters / " + feet + " feet");
			$(".user_wheel").html(better);
		}

	
	});
}

function generate_share(source, score) {
	gameimg="earth_facebookshare.png";
	
	//var fb_href="http://www.facebook.com/sharer/sharer.php?s=100&p[url]=www.intumate.com&p[images][0]=http://intumate.com/img/intumate.png&p[title]=My%20score%20on%20Intumate!&p[summary]=My%20intuition%20is%20better%20than%20" + score + "%25%20of%20the%20rest%20of%20the%20world!%0A%0AThink%20you%20can%20do%20better?%20prove%20it.%0Ahttp://www.intumate.com";
	var tw_href="http://twitter.com/home?status=My%20intuition%20is%20better%20than%20" + score + "%25%20of%20the%20rest%20of%20the%20world!%0A%0AThink%20you%20can%20do%20better?%20prove%20it.%0Ahttp://www.intumate.com";
	var fb_href="https://www.facebook.com/dialog/feed?app_id=568515256554117&display=popup&name=Better than " + score + "% of the rest of the world!" + "&link=http://www.intumate.com&redirect_uri=http://www.intumate.com/closewindow.html&picture=http://www.intumate.com/img/" + gameimg;
	
	if (source == "final") {
		$("#score_dialog_fb_share").attr("onclick", "myPopup('" + fb_href + "');");
		$("#score_dialog_tw_share").attr("onclick", "myPopup('" + tw_href + "');");
	}
}

function myPopup(url) {
	window.open( url, "myWindow", "status = 1, height = 500, width = 360, resizable = 0" );
	}
	
function close_dialog() {
	
	$('#resultdialog').dialog("close");
}

function diag_subscribe() {
	
	window.scrollTo(0,document.body.scrollHeight);
	close_dialog();
}

function show_dialog() {
	
	var opt = {
	        autoOpen: false,
	        modal: true,
	        width: "90%",
	        height: "auto",
	        draggable:false,
	        title: 'Awesome!',
	        show: 'fade', 
	        hide: 'fade'
	};
	
	
	
	
	$('#resultdialog').css('z-index','9999999');
	var mydialog = $('#resultdialog').dialog(opt);
	
	mydialog.dialog('option', 'dialogClass', 'noTitleStuff');
	
	
    var score = Math.ceil($("#totalscore").val()/3);
    
    $("#showscore").html(score);
    
    generate_share("final", score);
    
	mydialog.dialog("open");
    $('span.stars').stars(score);
}
